package Demo;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;
    private long delay;
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.delay = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getDelay() {
        return delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.getDelay() - o.getDelay());
    }
}
public class MyTimer {
//    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>((t1,t2) -> {
//        return (int) (t1.getDelay() - t2.getDelay());
//    });
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread( () -> {
           while (true) {
              synchronized (locker) {
                  while (queue.isEmpty()) {
                      try {
                          locker.wait();
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
                  MyTimerTask task = queue.peek();
                  long curTime = System.currentTimeMillis();
                  while (task.getDelay() > curTime) {
                      try {
                          locker.wait(task.getDelay() - curTime);
                          task = queue.peek();
                          curTime = System.currentTimeMillis();
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
                  task.getRunnable().run();
                  queue.poll();
              }
           }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }
}

class MyMain {
    public static void main(String[] args) {
        MyTimer t = new MyTimer();
        t.schedule( () -> {
            System.out.println("执行任务: 3000毫秒");
        },3000);
        t.schedule( () -> {
            System.out.println("执行任务: 2000毫秒");
        },2000);
        t.schedule( () -> {
            System.out.println("执行任务: 1000毫秒");
        },1000);
    }
}
